package com.efounder.agency.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.activity.AbActivity;
import com.efounder.agency.utils.TableGenerator;
import com.efounder.agency.utils.TaskDataParser;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.forwechat.BaseApp;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AndroidEnvironmentVariable;
import com.efounder.util.GlobalMap;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.view.titlebar.AbTitleBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/*
 * @author yqs
 * 任务中心详情界面
 */
public class TaskDetailDynamicActivity extends AbActivity implements
        OnClickListener {

    private static final String TAG = "TaskDetailDynamicActivity";

    AbTitleBar mTitleBar;

    LinearLayout scrollLinearLayout;

    EFRowSet flowRowSet = null;
    String systemType;// 系统类型 OA 或者 合同管理 CONTRACT
    String itemId;// 请求的详情页数据的id
    String usereId;// 用户id
    String userName;// 用户名
    String password;// 用户密码
    String typeString;// 判断代办还是已办
    Boolean isLock = false;// 公文审批是否锁定，如果锁定就不能点击操作按钮
    Boolean canUse = true;// 合同管理按钮是否可用，有的不允许移动端操作

    private TableGenerator tableGenerator;
    private TaskDataParser taskDataParser;
    private EFDataSet tableDataSet;
    AsyncTask<Void, Void, JResponseObject> asyncTask;
    AsyncTask<Void, Void, JResponseObject> cannelAsyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("", "------===========生命周期测试：onCreate");
        BaseApp.actManager.putActivity(TAG, this);
        setAbContentView(R.layout.task_detail_dynamic_activity);
        initView();
        initData();
    }

    @Override
    protected void onStart() {
        Log.i("", "------===========生命周期测试：onStart");
        super.onStart();
    }

    @Override
    protected void onRestart() {
        Log.i("", "------===========生命周期测试：onRestart");
        super.onRestart();
    }

    @Override
    protected void onResume() {
        Log.i("", "------===========生命周期测试：onResume");
        super.onResume();
    }

    @Override
    protected void onPause() {
        Log.i("", "------===========生命周期测试：onPause");
        super.onPause();

    }

    @Override
    protected void onStop() {
        Log.i("", "------===========生命周期测试：onStop");
        super.onStop();
        if (asyncTask != null) {
            asyncTask.cancel(true);
        }

    }

    @Override
    protected void onDestroy() {
        Log.i("", "------===========生命周期测试：onDestroy");
        super.onDestroy();
        if (asyncTask != null) {
            asyncTask=null;
        }
    }
    /**
     * 初始化view
     */
    private void initView() {

        mTitleBar = this.getTitleBar();
        mTitleBar.setTitleText("单据信息");
        mTitleBar.setLogo(R.drawable.ef_title_view_back);
        mTitleBar.clearRightView();
        mTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);
        mTitleBar.setLogoOnClickListener(this);

        // 得到bundle传递的数据
        Bundle bundle = getIntent().getBundleExtra("dataSource");
        if (bundle != null) {
            flowRowSet = (EFRowSet) bundle.getSerializable("data");
            systemType = (String) bundle.getSerializable("system");
            itemId = flowRowSet.getString("itemid", "");
            typeString = bundle.getString("type");
            Log.i(TAG, typeString);
        }

        if (flowRowSet.getString("field3", "").equals("请在PC端处理")) {
            canUse = false;
        }

        scrollLinearLayout = (LinearLayout) findViewById(R.id.scrollLinearLayout);

        // 初始化tableGenerator
        String cookie = GlobalMap.getProperty(systemType + "Id", "");
        tableGenerator = new TableGenerator(this, cookie, systemType);
        taskDataParser = new TaskDataParser(this);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        usereId = AndroidEnvironmentVariable.getUserID();// 用户id
        userName = AndroidEnvironmentVariable.getUserName();// 用户名
        password = AndroidEnvironmentVariable.getPassword();// 用户密码
        // 根据itemid请求数据
        if (flowRowSet != null) {

            Log.i(TAG, itemId);
            Log.i(TAG, "systemtype:" + systemType);

            loadDataByNet();
        } else {
            Toast.makeText(this, "获取数据失败！", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onClick(View v) {

        int id = v.getId();
        if (v == mTitleBar.getLogoView()) {
            //国勘oa进行解锁操作
            cannelLockFile();
            // BaseApp.actManager.removeActivity(TAG);
        }
    }

    /**
     * 显示或者隐藏gridlayout
     *
     * @param layout
     */
    private void showOrHideGridLay(LinearLayout layout, ImageView imageView,
                                   TextView textView) {
        if (layout.getVisibility() == View.VISIBLE) {
            layout.setVisibility(View.GONE);
            textView.setTextColor(this.getResources().getColor(R.color.shenhui));
            // textView.setTextColor(this.getResources().getColor(R.color.black));
            imageView.setImageDrawable(this.getResources().getDrawable(
                    R.drawable.bills_dowm));
        } else if (layout.getVisibility() == View.GONE) {
            layout.setVisibility(View.VISIBLE);
            textView.setTextColor(this.getResources().getColor(
                    R.color.billdetail_title));
            imageView.setImageDrawable(this.getResources().getDrawable(
                    R.drawable.bills_top));
        }

    }

    /**
     * 通过网络 加载数据
     */
    private void loadDataByNet() {
        asyncTask = new AsyncTask<Void, Void, JResponseObject>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // 加载dialog显示
                LoadingDataUtilBlack.show(TaskDetailDynamicActivity.this);
            }

            @Override
            protected JResponseObject doInBackground(Void... params) {

                JResponseObject RO = null;
                // 判断是OA的还是合同的详情信息，以此来向服务器请求数据
                if (systemType.equals("OA") || systemType.equals("ZYYTJG")
                        || systemType.equals("NMYTFGS")
                        || systemType.equals("PGYTFGS")
                        || systemType.equals("KTJFGS")
                        || systemType.equals("ZYYTFGS")) {
                    RO = getOADate(systemType, itemId);
                } else if (systemType.equals("CONTRACT")) {
                    RO = getContactDate(itemId);
                } else if (systemType.equals("FFS")) {// 费用报销
                    RO = getFFSData(itemId);
                } else if (systemType.equals("GKOA")
                        || systemType.equals("GKZBOA")) {// 国勘OA以及国勘总部OA
                    RO = getGKOAData(itemId);
                }
                return RO;
            }

            @Override
            protected void onPostExecute(JResponseObject result) {

                super.onPostExecute(result);
                LoadingDataUtilBlack.dismiss();
                if (result != null) {
                    @SuppressWarnings("unused")
                    List<List<EFRowSet>> lists = new ArrayList<List<EFRowSet>>();
                    @SuppressWarnings("unchecked")
                    Map<String, Map<String, EFDataSet>> map = result
                            .getResponseMap();
                    // 1 DataSet
                    EFDataSet rootDataSet = (EFDataSet) map.get(systemType);

                    tableDataSet = taskDataParser.parseFormData(rootDataSet);
                    if (tableDataSet == null) {
                        ToastUtil.showToast(TaskDetailDynamicActivity.this, "数据加载失败，请联系管理员");
                        return;
                    }

                    @SuppressWarnings("unchecked")
                    List<EFRowSet> tableRowSets = tableDataSet.getRowSetArray();
                    if (tableRowSets != null) {

                        // 1.生成一级item
                        LayoutInflater inflater = getLayoutInflater();
                        for (int i = 0; i < tableRowSets.size(); i++) {
                            EFRowSet tableEfRowSet = tableRowSets.get(i);
                            final ViewGroup oneLayout = (ViewGroup) inflater
                                    .inflate(
                                            R.layout.task_detail_dynamic_activity_one_item,
                                            scrollLinearLayout, false);
                            final RelativeLayout relativeLayout = (RelativeLayout) oneLayout
                                    .findViewById(R.id.oa_parenttitle);
                            final LinearLayout linearLayout = (LinearLayout) oneLayout
                                    .findViewById(R.id.contentLinearLayout);
                            TextView titleTextView = (TextView) oneLayout
                                    .findViewById(R.id.one_title);
                            String title = tableEfRowSet.getString("title", "");// 标题
                            String expend = tableEfRowSet.getString("expend",
                                    "");// 是否默认展开
                            if (expend.equals("true")) {
                                linearLayout.setVisibility(View.VISIBLE);
                                ImageView imageView = (ImageView) oneLayout
                                        .findViewById(R.id.img_arrow1);
                                TextView textView = (TextView) oneLayout
                                        .findViewById(R.id.one_title);
                                textView.setTextColor(getResources().getColor(
                                        R.color.billdetail_title));
                                imageView
                                        .setImageResource(R.drawable.bills_top);

                            }

                            if (title.contains("锁定")) {
                                isLock = true;
                            }
                            oneLayout.setTag(i);

                            titleTextView.setText(title);
                            scrollLinearLayout.addView(oneLayout);
                            // 设置点击事件监听
                            relativeLayout
                                    .setOnClickListener(new OnClickListener() {

                                        @Override
                                        public void onClick(View v) {

                                            ImageView imageView = (ImageView) oneLayout
                                                    .findViewById(R.id.img_arrow1);
                                            TextView textView = (TextView) oneLayout
                                                    .findViewById(R.id.one_title);
                                            showOrHideGridLay(linearLayout,
                                                    imageView, textView);
                                        }
                                    });

                            // 2.生成二级view
                            // @SuppressWarnings("unchecked")
                            // List<EFRowSet> trRowSets =
                            // tableEfRowSet.getChildDataSet().getRowSetArray();
                            @SuppressWarnings("deprecation")
                            ViewGroup tableLayout = tableGenerator
                                    .generateTable(tableEfRowSet,
                                            getWindowManager()
                                                    .getDefaultDisplay()
                                                    .getWidth());
                            linearLayout.addView(tableLayout);

                        }

                        // 判断是否是OA或者费用报销，添加操作按钮
                        if (systemType.equals("OA")
                                || systemType.equals("ZYYTJG")
                                || systemType.equals("NMYTFGS")
                                || systemType.equals("PGYTFGS")
                                || systemType.equals("KTJFGS")
                                || systemType.equals("ZYYTFGS")
                                || systemType.equals("FFS")
                                || systemType.equals("GKOA")
                                || systemType.equals("GKZBOA")
                                || systemType.equals("CONTRACT")) {
                            // 如果是待办才显示操作按钮
                            if ((typeString.equals("db") || typeString
                                    .equals("bl")) && isLock != true) {
                                addOperationButton(rootDataSet);
                            }

                        }
                    }
                }


            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
                Log.i(TAG, "asyncTask--onCancelled");
            }

        };
        asyncTask.executeOnExecutor(Executors.newCachedThreadPool());
    }

    /**
     * 获取公文审批（OA）数据
     *
     * @return
     */
    private JResponseObject getOADate(String systemType, String itemId) {
        // 创建PO
        JParamObject PO = JParamObject.Create();
        JResponseObject RO = null;
        String tokenConId = GlobalMap.getProperty(systemType + "Id",
                "");

        PO.SetValueByParamName("WB_SYS_KEY", systemType);
        PO.SetValueByParamName(systemType + "_params_userid", usereId);
        PO.SetValueByParamName(systemType + "_params_pwd", password);
        // PO.SetValueByParamName(systemType+"_params_type", "db");
        PO.SetValueByParamName(systemType + "_params_type", typeString);
        PO.SetValueByParamName(systemType + "_params_tokenIDFromMoblie",
                tokenConId);
        PO.SetValueByParamName(systemType + "_params_itemId", itemId);
        PO.SetValueByParamName(systemType + "_systemmethod", "GetDetailHandler");

        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
            System.out.println("..........");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RO;
    }

    /**
     * 获取合同数据
     *
     * @return
     */
    private JResponseObject getContactDate(String itemId) {
        // 创建PO
        JParamObject PO = JParamObject.Create();
        JResponseObject RO = null;
        String tokenConId = GlobalMap.getProperty("CONTRACTId", "");
        PO.SetValueByParamName("WB_SYS_KEY", "CONTRACT");
        // PO.SetValueByParamName("CONTRACT_params_userid", usereId);
        // PO.SetValueByParamName("CONTRACT_params_pwd", password);
        if ("db".equals(typeString)) {
            PO.SetValueByParamName("CONTRACT_params_type", "0");
        } else if ("yb".equals(typeString)) {
            PO.SetValueByParamName("CONTRACT_params_type", "1");
        }
        // PO.SetValueByParamName("CONTRACT_params_type", "1");
        PO.SetValueByParamName("CONTRACT_params_msgid", itemId);
        PO.SetValueByParamName("CONTRACT_params_tokenIDFromMoblie", tokenConId);
        PO.SetValueByParamName("CONTRACT_systemmethod",
                "GetApprovalDetailHandler");
        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
            System.out.println("..........");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RO;
    }

    /**
     * 获取费用报销数据
     *
     * @return
     */
    private JResponseObject getFFSData(String itemId) {
        // 创建PO
        JParamObject PO = JParamObject.Create();
        JResponseObject RO = null;
        String tokenConId = GlobalMap.getProperty(systemType + "Id",
                "");

        PO.SetValueByParamName("WB_SYS_KEY", "FFS");
        PO.SetValueByParamName("FFS_params_type", typeString);
        PO.SetValueByParamName("FFS_systemmethod", "GetDetailHandler");
        PO.SetValueByParamName("FFS_params_tokenIDFromMoblie", tokenConId);

        PO.SetValueByParamName("FFS_params_itemID", itemId);

        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
            System.out.println("..........");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RO;
    }

    /**
     * 获取国勘OA 国勘总部数据
     *
     * @return
     */
    private JResponseObject getGKOAData(String itemId) {
        // 创建PO
        JParamObject PO = JParamObject.Create();
        JResponseObject RO = null;
        String tokenConId = GlobalMap.getProperty(systemType + "Id",
                "");

        PO.SetValueByParamName("WB_SYS_KEY", systemType);
        if ("db".equals(typeString)) {// 待办
            PO.SetValueByParamName(systemType + "_params_type", "0");
        } else if ("yb".equals(typeString)) {// 已办
            PO.SetValueByParamName(systemType + "_params_type", "1");
        }
        if ("dy".equals(typeString)) {//待阅
            PO.SetValueByParamName(systemType + "_params_type", "2");
        } else if ("yy".equals(typeString)) {// 已阅
            PO.SetValueByParamName(systemType + "_params_type", "3");
        }
        PO.SetValueByParamName(systemType + "_systemmethod", "GetDetailHandler");
        PO.SetValueByParamName(systemType + "_params_tokenIDFromMoblie", tokenConId);
        PO.SetValueByParamName(systemType + "_params_unid", itemId);

        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
            System.out.println("..........");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RO;
    }

    private void addOperationButton(final EFDataSet rootDataSet) {
        Button operationButton = new Button(this);
        operationButton.setText("操作");
        operationButton.setTextSize(16);
        operationButton.setTextColor(getResources().getColor(R.color.title_TextColor));
        operationButton.setBackgroundColor(Color.TRANSPARENT);
        mTitleBar.addRightView(operationButton);
        mTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);

        operationButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!canUse) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            TaskDetailDynamicActivity.this);

                    builder.setTitle("提示")
                            .setMessage("该操作只能在pc端处理")
                            .setPositiveButton(R.string.common_text_confirm,
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            dialog.dismiss();

                                        }
                                    }).show();
                    return;
                }
                Intent intent = null;
                if ("FFS".equals(systemType)) {
                    intent = new Intent(TaskDetailDynamicActivity.this,
                            FFSApprovalDynamicActivity.class);
                } else if ("CONTRACT".equals(systemType)) {
                    intent = new Intent(TaskDetailDynamicActivity.this,
                            ContractApprovalDynamicActivity.class);
                } else if ("GKOA".equals(systemType)) {
                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
                    Class<?> clazz = null;
                    try {
                        clazz = loader.loadClass("com.efounder.guokan.activity.GKOAApprovalDynamicActivity");
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    intent = new Intent(TaskDetailDynamicActivity.this,
                            clazz);
                } else {
                    intent = new Intent(TaskDetailDynamicActivity.this,
                            OAApprovalDynamicActivity.class);
                }
                intent.putExtra("rootDataSet", rootDataSet);
                intent.putExtra("systemtype", systemType);
                intent.putExtra("itemId", itemId);
                intent.putExtra("type", typeString);
                startActivityForResult(intent, 0);
                // startActivity(intent);
                // List<Map<String, Object>> operationData =
                // taskDataParser.parseOperation(rootDataSet);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        Log.i("", "-------onActivityResult:" + TAG);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            this.setResult(RESULT_OK);
            // 关闭Activity
            BaseApp.actManager.removeActivity(TAG);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            cannelLockFile();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 返回的时候 解锁文件
     */
    private void cannelLockFile() {
        if (!"GKOA".equals(systemType)) {
            BaseApp.actManager.removeActivity(TAG);
            return;
        }
        if (("0".equals(typeString) || ("db".equals(typeString)))) {
            cannelAsyncTask = new AsyncTask<Void, Void, JResponseObject>() {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // 加载dialog显示
                    LoadingDataUtilBlack.show(TaskDetailDynamicActivity.this, "解锁中..");
                }

                @Override
                protected JResponseObject doInBackground(Void... params) {
                    JResponseObject RO = null;
                    JParamObject PO = JParamObject.Create();
                    String tokenConId = GlobalMap.getProperty(systemType + "Id",
                            "");
                    PO.SetValueByParamName("WB_SYS_KEY", "GKOA");
                    PO.SetValueByParamName("GKOA_systemmethod", "GetCancelLock");
                    PO.SetValueByParamName("GKOA_params_tokenIDFromMoblie", tokenConId);
                    PO.SetValueByParamName("GKOA_params_oaCancel", itemId);
                    try {
                        RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return RO;
                }

                @Override
                protected void onPostExecute(JResponseObject result) {
                    super.onPostExecute(result);
                    LoadingDataUtilBlack.dismiss();
                    BaseApp.actManager.removeActivity(TAG);
                }
            };
            cannelAsyncTask.executeOnExecutor(Executors.newCachedThreadPool());
        }else {
            BaseApp.actManager.removeActivity(TAG);
        }
    }

}